#!/usr/bin/env python3
#: Title        : iphone_ch
#: Author       : "John Lehr" <slo.sleuth@gmail.com>
#: Date         : 10/04/2011
#: Version      : 2.0.0
#: Description  : Dump/interpret iphone call_history.db call table 
#: Options      : None
#: License      : GPLv3

#: 03/22/2011   : v1.0.0 Initial Release
#: 05/04/2011   : v1.0.1 added extended output formats, updated code schema
#: 10/04/2011   : v2.0.0 migrated to python3 from bash
#: 10/07/2011   : v2.0.1 Corrected db version compatibility error, updated id field to read 'None' if no corresponding AB entry                

import sqlite3, argparse
from time import strftime, localtime, gmtime

flag = {4 : 'Incoming', 5 : 'Outgoing', 8 : 'Cancelled'}

def printdb(args):
    '''Prints the rows from the iPhone callhistory.db, interpreting the flags.'''
    
    if not args.noheader:
        print('File: "{}"'.format(args.database))
        print('Record #,Time,Type,Phone Number,AdressBook ID,Duration')
    
    try: 
        conn = sqlite3.connect(args.database)
        c = conn.cursor()

        # Read specific fields in the database to accomodate different versions of call_history.db
        for ROWID, address, date, duration, flags, id in c.execute('select  ROWID, address, date, duration, flags, id from call'):

            #convert flags object to flag dictionary value
            type = flag.get(flags, 'Unknown')

            if id == -1:
                id = None
    
            #convert timestamp to local time or utc
            if args.utc:
                time = strftime('%Y-%m-%d %H:%M:%S (UTC)', gmtime(date))
            else:
                time = strftime('%Y-%m-%d %H:%M:%S (%Z)', localtime(date))

            print('{},{},{},{},{},{}'.format(ROWID, time, type, address, id, duration))

    except sqlite3.Error:
            print('SQLite Error: wrong or incompatible database')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Process iPhone call history database.',
        epilog='Converts timestamps to local time and interprets flag values.  Prints to stdout.')
    parser.add_argument('database', help='an iPhone call_history.db database')
    parser.add_argument('-n', '--no-header', dest='noheader', action='store_true', help='do not print filename or column header')
    parser.add_argument('-u', '--utc', dest='utc', action='store_true', help='Show UTC time instead of local')
    parser.add_argument('-V', '--version', action='version', version='%(prog)s v2.0.1')

    args = parser.parse_args()

    printdb(args)
